import {http, includes} from 'libs'
import {makeAutoObservable} from 'mobx'

class Store {
  constructor() {
    this.set = (k, v) => {
      if (v && v.nativeEvent) v = v.target.value
      this[k] = v
    }
    this.eSet = k => e => this.set(k, e)
    this.vSet = (k, v) => () => this.set(k, v)
    makeAutoObservable(this)
  }

  records = []
  record = {}
  fetching = false
  formVisible = false

  f_name = ''
  f_time = null
  f_status = ''

  get dataSource() {
    let data = this.records
    if (this.f_status) data = data.filter(x => x.is_active === (this.f_status === '1'))
    if (this.f_name) data = data.filter(x => includes(x.username, this.f_name))
    if (this.f_time) data = data.filter(x => x.last_login.startsWith(this.f_time.format('YYYY-MM-DD')))
    return data
  }

  fetchRecords = () => {
    this.fetching = true
    http.get('/api/purchase/return/')
      .then(res => this.set('records', res))
      .finally(() => this.set('fetching', false))
  }

  fetchRecord = (id) => {
    this.fetching = true
    http.get('/api/purchase/return/?id=' + id)
      .then(res => this.set('record', res))
      .finally(() => this.set('fetching', false))
  }

  showForm = (info) => {
    this.record = info || {}
    this.formVisible = true
  }

}

export default new Store()